package net.runman.controller;


import java.util.Date;

import net.runman.event.UserSaveEvent;
import net.runman.model.TLinks;
import net.runman.model.User;
import net.runman.service.LinksService;
import net.runman.service.UserService;
import net.runman.utils.SpringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired private UserService userService;

	@Autowired private LinksService linksService;
	// 邮件发送参考
	// spring boot mail-> http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-email
	// spring mail-> http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#mail
	@Autowired private JavaMailSender sender;

	@RequestMapping(value = { "/", "/index.html" }, method = RequestMethod.GET)
	public String index(Model model, String t) {
		logger.info("t:{}", t);

		User user = new User();
		user.setEmail("596392912@qq.com");
		user.setUsername("Dreamlu");

		int updateCount = userService.addUser(user);
		// 发布用户保存的事件
		SpringUtils.getContext().publishEvent(new UserSaveEvent(user));

		logger.error(Thread.currentThread().getName() + "\tuser id:{} updateCount:{}", user.getId(), updateCount);

		// 邮件发送
		SimpleMailMessage templateMessage = new SimpleMailMessage();
		templateMessage.setTo("596392912@qq.com");
		templateMessage.setSubject("测试邮件哦");
		templateMessage.setText("hello");
		templateMessage.setFrom("dreamlu<dreamlu@139.com>");
//		sender.send(templateMessage);
		
		TLinks links = new TLinks();
		links.setLinkName("hello");
		links.setLinkUrl("http:www.baidu.cn");
		links.setLinkImage("image");
		links.setLinkVisible("y");
		links.setLinkOwner(1l);
		links.setLinkTarget("target");
		links.setLinkUpdated(new Date());
		links.setLinkDescription("测试");
		linksService.saveLinks(links);

		model.addAttribute("user", userService.getUser(user.getId()));
		return "index";
	}

	/**
	 * 测试热部署，用于开发环境
	 * 项目下命令行执行：mvn spring-boot:run
	 * 或者：项目 -> Run As -> Maven Build… -> 在Goals框中输入：spring-boot:run
	 * 
	 * 详情：http://docs.spring.io/spring-boot/docs/current/reference/html/howto-hotswapping.html
	 * 注意：https://github.com/spring-projects/spring-loaded/issues/80
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public @ResponseBody String test(Model model) {
		return "hello中国";
	}
}
